let q = ['a', 'b', 'd', 'e', 'h', 'c', 'f', 'g'];
let z = ['d', 'b', 'h', 'e', 'a', 'f', 'c', 'g'];

function Node(val) {
    this.value = val;
    this.left = null;
    this.right = null;
}

function begin(q, z) {
    if (q == null || z == null || q.length == 0 || z.length == 0 || q.length != z.length) return [];
    let root = q[0];
    let rootNode = new Node(root);
    let rootIndex = z.indexOf(root);
    let qLeft = q.slice(1, rootIndex + 1);
    let qRight = q.slice(rootIndex + 1, q.length);
    let zLeft = z.slice(0, rootIndex);
    let zRight = z.slice(rootIndex + 1, z.length);
    rootNode.left = begin(qLeft, zLeft);
    rootNode.right = begin(qRight, zRight);
    return rootNode;
}

console.log(begin(q, z));